package main.java.com.rmisorter;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

@SuppressWarnings({"rawtypes", "unused"})
public class ListJoiner implements Observer {
	private Comparable[] joinedList;
	private Comparable[][] tempList;
	private int listSize, numberOfLists, receivedLists;
	
	public ListJoiner(int listSize, int numberOfLists) {
		this.listSize = listSize;
		this.joinedList = new Comparable[listSize];
		this.numberOfLists = numberOfLists;
		this.tempList = new Comparable[numberOfLists][];
		this.receivedLists = 0;
	}
	
    public void join() throws NullPointerException {
    	int i, j, index = 0;

    	for (i = 0; i < this.numberOfLists; i++) {
    		for (j = 0; j < tempList[i].length; j++) {
    			this.joinedList[index] = tempList[i][j];
    		
    			index++;
    		}
    	}
    	
    	printJoinedList();
    }

	public void printJoinedList() {
		int i;
		
		printHeader();
		
		for (i = 0; i < this.joinedList.length; i++) {
			System.out.println((i+1) + " " + this.joinedList[i]);
		}
	}
	
	private void printHeader() {
		System.out.println("++++++++++++++++++++++++++++");
		System.out.println("+        RESULT            +");
		System.out.println("++++++++++++++++++++++++++++");
	}

	@Override
	public synchronized void update(Observable o, Object arg) {
		Comparable[] sortedList = (Comparable[]) arg;
		int threadNumber = ((SorterThread) o).getThreadNumber();
		
		this.tempList[threadNumber-1] = new Comparable[sortedList.length];
		this.tempList[threadNumber-1] = sortedList;
		this.receivedLists++;
			
		if (threadsAreReady()) {
			join();
		}
		
	}
	
	private boolean threadsAreReady() {
		return (this.numberOfLists == this.receivedLists);
	}
}
